<script setup>
import { User, Lock } from '@element-plus/icons-vue'
import { ref } from 'vue'
import { ElMessage } from 'element-plus'
import { userRegisterService, userLoginService } from '@/api/user.js'
import { useTokenStore } from '@/stores/token.js'
import { useRouter } from 'vue-router'

// 控制注册与登录表单的显示，默认显示注册
const isRegister = ref(false)

// 定义数据模型
const registerData = ref({
    username: '',
    password: '',
    rePassword: '',
    email: ''
})

const loginData = ref({
    username: '',
    password: ''
})

// 校验密码的函数
const checkRePassword = (rule, value, callback) => {
    if (value === '') {
        callback(new Error('请再次确认密码'))
    } else if (value !== registerData.value.password) {
        callback(new Error('请确保两次输入的密码一样'))
    } else {
        callback()
    }
}

// 定义表单校验规则
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 5, max: 16, message: '长度为5~16位非空字符', trigger: 'blur' }
    ],
    rePassword: [
        { validator: checkRePassword, trigger: 'blur' }
    ]
}

const router = useRouter()
const tokenStore = useTokenStore()

// 注册用户
const registerUser = async () => {
    try {
        const result = await userRegisterService(registerData.value)
        ElMessage.success(result.msg ? result.msg : '注册成功')
        isRegister.value = false
        router.push('/login')
        clearRegisterData()
    } catch (error) {
        ElMessage.error(error.response?.data?.message || '注册失败')
    }
}

// 登录用户
const loginUser = async () => {
    try {
        const result = await userLoginService(loginData.value)
        ElMessage.success(result.msg ? result.msg : '登录成功')
        // 存储token并处理可能的错误
        try {
            tokenStore.setToken(result.data)
            // 清除登录表单
            loginData.value = { username: '', password: '' }
            // 跳转到文章管理页面避免循环
            router.push('/article/manage')
        } catch (error) {
            ElMessage.error('登录状态保存失败，请重试')
            console.error('Token存储失败:', error)
        }
    } catch (error) {
        ElMessage.error(error.response?.data?.message || '登录失败')
    }
}

// 清空注册数据
const clearRegisterData = () => {
    registerData.value = {
        username: '',
        password: '',
        rePassword: '',
        email: ''
    }
}
</script>

<template>
    <!-- 保持原有模板内容不变 -->
</template>

<style lang="scss" scoped>
/* 保持原有样式不变 */
</style>
